"""
    Simple lookup for viewing temporary payment records table.
"""

from urllib import urlencode
from turbogears import widgets, redirect, expose, validate, flash, identity
from mnemoply import model
from mnemoply.controllers import Report
from mnemoply.controllers.lookup import LookupController, TableCol, TableLookupDataSource
from mnemoply.controllers.crud import CRUDController, ItemTab
from mnemoply.mass_actions import MassAction, MassActionForm, registry
from mnemoply.widgets import DictionaryField, CustomerField, StudentField, CouponField
from mnemoply.utils import objs2ids, update_with, cleanup_kw, get_id_or_empty, format_date, drop_key_if_exists

class MACreateRecords(MassAction):
    target_class = model.TemporaryPaymentRecord
    name = "__create_records__"
    title = _("Create records")

    form = MassActionForm(name=name,
        fields=[
            widgets.TextField(name="number", label=_("Amount of new records")),
            DictionaryField(
                    name="organization_id",
                    model_object_name='Organization',
                    not_empty=True,
                    label=_("Organization")),
            DictionaryField(
                    name="trend_id",
                    model_object_name='Trend',
                    not_empty=True,
                    label=_("Trend"))
            ])

    def call(self, _, number, organization_id, trend_id):
        organization = model.Organization.get(int(organization_id))
        trend = model.Trend.get(int(trend_id))
        information_source = model.InformationSource.byStringId('unknown')
        new_records = []
        try:
            number = int(number)
            for _ in xrange(0, number):
                new_records.append(model.TemporaryPaymentRecord(
                    organization=organization,
                    trend=trend,
                    informationSource=information_source,
                    tempSurname='',
                    tempForename='',
                    tempPatronymic='',
                    phone='',
                    register=None,
                ))
        except:
            pass
        return registry.getAction('TemporaryPaymentRecord', 'temporary_payment_records_print').call(new_records)

class MACreateAgreement(MassAction):
    target_class = model.TemporaryPaymentRecord
    name = "create_agreement"
    title = _("Create agreement")

    form = MassActionForm(name=name,
        fields=[
            CustomerField(
                name="customer_id",
                label=_("Customer"))
            ])

    def call(self, objs, customer_id=None):
        """Create agreement for first selected temporary record. Redirect user to `/StudentAgreement/show_form*`."""

        tpr = objs[0]

        if tpr.payment <= 0:
            flash(_("Payment <= 0"))
            raise redirect("/TemporaryPaymentRecord")

        if tpr.studentAgreement:
            flash(_("Agreement is not empty"))
            raise redirect("/TemporaryPaymentRecord")

        common_kw = dict(
            organization_id=get_id_or_empty(tpr.organization),
            trend_id=get_id_or_empty(tpr.trend),
            customer_tariff_id=get_id_or_empty(tpr.tariff),
            register_id=get_id_or_empty(tpr.register),
            information_source_id=get_id_or_empty(tpr.informationSource),
            event_id=get_id_or_empty(tpr.event),
            date_enter_agreement_view=format_date(tpr.date),
            date_enter_agreement=str(tpr.date),
            )

        def update_clean_encode(kw):
            kw.update(common_kw)
            kw = cleanup_kw(kw)
            return dict([[k, v.encode('utf-8')] for k, v in kw.items()])

        if not tpr.student and customer_id is None:
            kw = dict(
                student_surname=tpr.tempSurname,
                student_forename=tpr.tempForename,
                student_patronymic=tpr.tempPatronymic,
                customer_phone=tpr.phone,
                temppr=str(tpr.id),
                )

            raise redirect("/StudentAgreement/show_form?" +
                           urlencode(update_clean_encode(kw)))

        if not tpr.student and customer_id is not None:
            kw = dict(
                student_surname=tpr.tempSurname,
                student_forename=tpr.tempForename,
                student_patronymic=tpr.tempPatronymic,
                customer=str(customer_id),
                temppr=str(tpr.id),
                )

            raise redirect("/StudentAgreement/show_form_without_student_with_customer?" +
                           urlencode(update_clean_encode(kw)))

        if tpr.student and customer_id is None:
            kw = dict(
                student=str(tpr.student.id),
                temppr=str(tpr.id),
                )

            raise redirect("/StudentAgreement/show_form_with_student_without_customer?" +
                           urlencode(update_clean_encode(kw)))

        if tpr.student and customer_id is not None:
            kw = dict(
                student=str(tpr.student.id),
                customer=str(customer_id),
                temppr=str(tpr.id),
                )

            raise redirect("/StudentAgreement/show_form_for_exist_student?" +
                           urlencode(update_clean_encode(kw)))

class MAPrint(MassAction):
    target_class = model.TemporaryPaymentRecord
    name = "temporary_payment_records_print"
    title = _("Print")
    read_only = True

    def call(self, objs):
        return Report.generate('TPRPrint',
            ids=objs2ids(objs),
        )

class MASetStudent(MassAction):
    target_class = model.TemporaryPaymentRecord
    name = "set_student"
    title = _("Set student")

    form = MassActionForm(name=name,
        fields=[
            StudentField(
                name="student_id",
                not_empty=True,
                label=_("Student"))
            ])

    def call(self, tprs, student_id):
        if student_id:
            s = model.Student.get(int(student_id))
            for t in tprs:
                if s.surname==t.tempSurname and s.forename==t.tempForename and s.patronymic==t.tempPatronymic:
                    t.student = s
                else:
                    self.flash_message = _("The student's name does not coincide")
        else:
            self.flash_message = _("Student not found")

class CouponItemTab(ItemTab):
    title = _("Coupon")
    name = "coupon_tab"
    template = "../tpr_coupon_tab"

    add_form = widgets.TableForm(
        fields=[
            CouponField(name='coupon_id', label=_("Coupon")),
        ],
        submit_text=_("Add"),
        action='add_coupon',
    )

    @validate(form=add_form)
    @expose()
    def add_coupon(self, obj, coupon_id):
        if coupon_id is not None:
            coupon = model.Coupon.get(int(coupon_id))
            coupon.temporaryPaymentRecord = obj
        raise redirect("./")

class TemporaryPaymentRecordController(LookupController, CRUDController):
    model_object = model.TemporaryPaymentRecord
    lookup_columns = [
        TableCol(name='id', caption=_('#')),
        TableCol(name='date', caption=_('Date')),
        TableCol(name='payment', caption=_('Amount')),
        TableCol(name='temp_surname', caption=_('Surname')),
        TableCol(name='temp_forename', caption=_('Forename')),
        TableCol(name='phone', caption=_('Phone number')),
        TableCol(name='trend', caption=_('Trend')),
        TableCol(name='organization', caption=_('Organization')),
        TableCol(name='cash_register', caption=_('Cash register'), hidden=True),
        TableCol(name='office', caption=_('Office'), hidden=True),
        TableCol(name='temp_patronymic', caption=_('Patronymic'), hidden=True),
        TableCol(name='student', caption=_('Student'), hidden=True),
        TableCol(name='is_agreement_created', caption=_('Is agreement created'), hidden=True),
        TableCol(name='coupon_number', caption=_('Coupon number'), hidden=True),
        TableCol(name='comment', caption=_('Comment'), hidden=True),
        TableCol(name='information_source', caption=_('Information source'), hidden=True),
        TableCol(name='event', caption=_('Event'), hidden=True),
    ]

    view_fields = [
        'studentID',
        'studentAgreementID',
        'payment',
        'date',
        'registerID',
        'comment',
        'tempSurname',
        'tempForename',
        'tempPatronymic',
        'phone',
        'informationSourceID',
        'eventID',
        'organizationID',
        'trendID',
        'tariffID',
    ]

    item_tabs = [CouponItemTab()]

    def _get_edit_fields(self, obj):
        fields = [
            'informationSourceID',
            'eventID',
            'comment',
        ]
        if obj.studentAgreement is None:
            fields = update_with(fields, [
                'organizationID',
                'trendID',
                'tariffID',
                ])
        if obj.student is None:
            fields = update_with(fields, [
                'tempSurname',
                'tempForename',
                'tempPatronymic',
                'phone',
                ])
        return fields

    def _update_kw(self, obj, kw):
        result = kw
        result = drop_key_if_exists(result, 'tg_exceptions')
        result = drop_key_if_exists(result, 'tg_source')

        result = drop_key_if_exists(result, 'studentID')
        result = drop_key_if_exists(result, 'studentAgreementID')
        result = drop_key_if_exists(result, 'date')
        result = drop_key_if_exists(result, 'payment')
        result = drop_key_if_exists(result, 'registerID')
        if obj.studentAgreement:
            result = drop_key_if_exists(result, 'organizationID')
            result = drop_key_if_exists(result, 'trendID')
            result = drop_key_if_exists(result, 'tariffID')
        if obj.student:
            result = drop_key_if_exists(result, 'tempSurname')
            result = drop_key_if_exists(result, 'tempForename')
            result = drop_key_if_exists(result, 'tempPatronymic')
            result = drop_key_if_exists(result, 'phone')
        return result

    def _delete_tg_errors(self, tg_errors):
        return drop_key_if_exists(tg_errors, 'registerID')

    def __init__(self):
        LookupController.__init__(self,
            data_source=TableLookupDataSource('temporary_payment_record_lookup'),
            columns=self.lookup_columns,
            mass_actions_class=self.model_object,
            title=self.model_object.model_title,
        )
        CRUDController.__init__(self, model_object=self.model_object)
        self.local_menu = []

exposed = TemporaryPaymentRecordController()
